var W = Object.defineProperty;
var R = Object.getOwnPropertySymbols;
var K = Object.prototype.hasOwnProperty,
    Z = Object.prototype.propertyIsEnumerable;
var O = (h, p, m) => p in h ? W(h, p, {
        enumerable: !0,
        configurable: !0,
        writable: !0,
        value: m
    }) : h[p] = m,
    v = (h, p) => {
        for (var m in p || (p = {})) K.call(p, m) && O(h, m, p[m]);
        if (R)
            for (var m of R(p)) Z.call(p, m) && O(h, m, p[m]);
        return h
    };
(function () {
    "use strict";
    window.ntcAppProxyPrefix = "a/d", window.ntcApiUrl = "https://checkout.nextcartpay.com";

    function h() {
        const e = Date.now();
        let t;
        return crypto.randomUUID ? t = crypto.randomUUID().replace(/-/g, "") : t = ("10000000-1000-4000-8000" + -
            1e11).replace(/[018]/g, o => (o ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> o / 4).toString(
            16)).replace(/-/g, ""), `${e}_${t}`
    }

    function p(e) {
        const o = `; ${document.cookie}`.split(`; ${e}=`);
        return o.length === 2 ? o.pop().split(";").shift() : ""
    }

    function m(e, t = window.location.href) {
        return new URL(t).searchParams.get(e)
    }

    function I() {
        const e = "ntc_customer_id";
        let t = localStorage.getItem(e);
        return t || (t = h().split("_")[1], localStorage.setItem(e, t)), t
    }

    function C() {
        const e = JSON.parse(localStorage.getItem("ntc_facebook_ads")) || {};
        return ["ad_id", "campaign_id", "adset_id"].reduce((t, o) => (t[o] = e[o] || "", t), {})
    }
    async function _(e, t = {}, o = 5e3) {
        let r, n;
        window.AbortController && (n = new AbortController, t.signal = n.signal);
        const a = new Promise((c, i) => {
            r = setTimeout(() => {
                n && n.abort(), i(new Error(`Request timeout after ${o}ms`))
            }, o)
        });
        try {
            const c = fetch(e, v({
                    credentials: "same-origin",
                    headers: v({
                        "Content-Type": "application/json"
                    }, t.headers || {})
                }, t)),
                i = await Promise.race([c, a]);
            if (!i.ok) {
                const u = await i.text().catch(() => "");
                throw new Error(`HTTP ${i.status} ${i.statusText} - ${u}`)
            }
            return await i.json()
        } finally {
            clearTimeout(r)
        }
    }

    function k() {
        return new Promise(e => {
            if (window.fbq) return e();
            const t = setInterval(() => {
                window.fbq && window.fbq.callMethod && (clearInterval(t), e())
            }, 50)
        })
    }

    function j(e = 5e3) {
        return new Promise((t, o) => {
            const r = Date.now();
            if (window.ttq && typeof window.ttq.track == "function") return t();
            const n = setInterval(() => {
                window.ttq && typeof window.ttq.track == "function" ? (clearInterval(n), t()) :
                    Date.now() - r > e && (clearInterval(n), o(new Error("ttq not ready")))
            }, 50)
        })
    }

    function P(e, t = null) {
        try {
            const o = new CustomEvent(e, {
                detail: t
            });
            document.dispatchEvent(o), console.log(`CustomEvent dispatched: ${e}`, t)
        } catch (o) {
            console.error(`Error dispatching ${e} event:`, o)
        }
    }

    function q() {
        const e = "ntc_first_landing_url";
        let t = localStorage.getItem(e);
        return t || (t = window.location.href, localStorage.setItem(e, t)), t
    }

    function S() {
        const e = "ntc_first_referrer_url";
        let t = localStorage.getItem(e);
        return t || (t = document.referrer || "", localStorage.setItem(e, t)), t
    }(async function () {
        const t = I();
        console.log("[init-customerId]:", t);
        const o = q();
        console.log("[init-ladingUrl]:", o);
        const r = S();
        console.log("[init-referrerUrl]:", r);
        const n = m("ad_id"),
            a = m("campaign_id"),
            c = m("adset_id"),
            i = {};
        n !== null && n !== "" && !isNaN(n) && (i.ad_id = n), a !== null && a !== "" && !isNaN(a) && (i.campaign_id =
            a), c !== null && c !== "" && !isNaN(c) && (i.adset_id = c), Object.keys(i).length > 0 &&
        localStorage.setItem("ntc_facebook_ads", JSON.stringify(i))
    })();
    const T = (function () {
        function e() {
            const o = document.createElement("style");
            o.innerHTML =
                `
            .loader-container {
                position: fixed;
                top: 0;
                left: 0;
                width: 100vw;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                background-color: rgba(255, 255, 255, 0);
                z-index: 9999;
                animation: fadeInBackground 3s forwards;
            }

            .custom-loader {
                width: 100px;
                height: 100px;
                border: 5px solid rgba(0, 0, 0, 0.1);
                border-radius: 50%;
                border-top-color: #0723af;
                animation: spin 1s ease-in-out infinite;
                position: relative;
            }

            .spinnerImage {
                width: 50px;
                height: 50px;
                background: url("") no-repeat center;
                background-size: contain;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }

            @keyframes spin {
                to { transform: rotate(360deg); }
            }

            @keyframes fadeInBackground {
                0% {
                    background-color: rgba(255, 255, 255, 0);
                }
                100% {
                    background-color: rgba(255, 255, 255, 1);
                }
            }
        `,
                document.head.appendChild(o);
            const r = document.createElement("div");
            return r.className = "loader-container", r.innerHTML =
                `
            <div class="custom-loader">&#8203;</div>
            <div class="spinnerImage">&#8203;</div>
        `,
                document.body.appendChild(r), r
        }
        let t = null;
        return {
            show: function () {
                t || (t = e()), t.style.display = "flex", document.body.style.overflow = "hidden"
            },
            hide: function () {
                t && (t.style.display = "none", document.body.style.overflow = "")
            }
        }
    })();
    async function $({
                         id: e,
                         quantity: t = 1
                     }) {
        if (!e) throw new Error("Missing variant id");
        return _("/cart/add.js", {
            method: "POST",
            body: JSON.stringify({
                id: e,
                quantity: t
            })
        })
    }
    async function b() {
        return _("/cart.js", {
            method: "GET"
        })
    }
    async function Q({
                         id: e,
                         quantity: t
                     }) {
        return _("/cart/update.js", {
            method: "POST",
            body: JSON.stringify({
                updates: {
                    [e]: t
                }
            })
        })
    }

    function H(e, t, o) {
        const {
            ad_id: r,
            campaign_id: n,
            adset_id: a
        } = C(), c = window.ntc.shop.country, i = window.ntc.shop.currency, u = I();
        return {
            checkout: {
                is_paypal: o,
                track: {
                    customer_id: u || "",
                    fb: {
                        fbc: p("_fbc"),
                        fbp: p("_fbp"),
                        ad_id: r,
                        campaign_id: n,
                        adset_id: a
                    },
                    tk: {
                        ttclid: p("ttclid"),
                        ttp: p("_ttp")
                    },
                    device: {
                        java_enabled: !1,
                        color_depth: window.screen.colorDepth,
                        screen_height: window.screen.height,
                        screen_width: window.screen.width,
                        user_agent: navigator.userAgent,
                        language: navigator.language,
                        time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone
                    },
                    btn_uid: t,
                    page: {
                        url: window.location.href,
                        referrer: document.referrer || "",
                        first_landing_url: q(),
                        first_referrer_url: S()
                    },
                    locale: {
                        country: c,
                        currency: i
                    }
                },
                cart: e
            }
        }
    }
    async function A(e, t, o) {
        var c;
        const r = H(e, t, o),
            n = window.ntc.shop.shopHandle,
            a = await _(`${window.ntcApiUrl}/api/checkout`, {
                method: "POST",
                headers: {
                    "X-Shop-Handle": n,
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(r)
            }, 1e4);
        if ((c = a == null ? void 0 : a.data) != null && c.id) {
            const i = a.data.redirect_url;
            i ? window.location.href = i : window.location.href =
                `/${window.ntcAppProxyPrefix}/checkout/${a.data.id}`
        } else window.location.href = "/cart"
    }

    function B(e) {
        if (!e) return null;
        const t = Array.from(document.querySelectorAll("form[action^='/cart/add']"));
        if (t.length === 0) return null;
        const o = e.getBoundingClientRect();
        let r = null,
            n = 1 / 0;
        return t.forEach(a => {
            const c = a.getBoundingClientRect(),
                i = Math.abs(c.top - o.top);
            i < n && (n = i, r = a)
        }), r
    }

    function E() {
        console.log("findFallbackVariantInput");
        let e = document.querySelector('input[name="id"]:not([class])');
        return e || (e = document.querySelector('input[name="id"]')), e
    }

    function D() {
        return console.log("findFallbackQuantityInput"), document.querySelector(
            "select[name='quantity'], input[name='quantity']")
    }

    function J(e) {
        var o, r;
        if (!e) return ((o = E()) == null ? void 0 : o.value) || null;
        let t = e.closest("form[action^='/cart/add']");
        if (t || (t = B(e)), t) {
            const n = t.querySelector("select[name='id'], input[name='id']");
            if (n) return n.value
        }
        return ((r = E()) == null ? void 0 : r.value) || null
    }

    function L(e) {
        var o, r;
        if (!e) return Number(((o = D()) == null ? void 0 : o.value) || 1);
        let t = e.closest("form[action^='/cart/add']");
        if (t || (t = B(e)), t) {
            const n = t.querySelector("select[name='quantity'], input[name='quantity']");
            if (n) return Number(n.value || 1)
        }
        return Number(((r = D()) == null ? void 0 : r.value) || 1)
    }
    async function g(e, t, o = !1, r = !1) {
        var n;
        e && e.preventDefault();
        try {
            T.show();
            let a = await b();
            if (o) {
                await A(a, t, r);
                return
            }
            const c = document.querySelector("#ntcProdPageCheckoutBtn"),
                i = J(c),
                u = L(c);
            if (console.info("quantity", u), console.info("variant id", i), !i) {
                console.error("empty variant id"), await A(a, t, r);
                return
            }
            const y = (n = a == null ? void 0 : a.items) == null ? void 0 : n.find(l => String(l.id) === String(
                i));
            y ? Number(y.quantity) !== u && (console.log("update cart item", i), await Q({
                id: i,
                quantity: u
            }), a = await b()) : (P("ntcAddToCart"), console.log("add cart item", i), await $({
                id: i,
                quantity: u
            }), a = await b()), await A(a, t, r)
        } catch (a) {
            console.error("Checkout error:", a)
        } finally {
            T.hide()
        }
    }
    window.ntcProdPageCheckoutBtn = e => g(e, "prod_page_checkout"), window.ntcProdPagePayPalBtn = e => g(e,
        "prod_page_paypal", !1, !0), window.ntcCartDrawerCheckoutBtn = e => g(e, "cart_drawer_checkout", !0),
        window.ntcCartDrawerPayPalBtn = e => g(e, "cart_drawer_paypal", !0, !0), window.ntcCartPageCheckoutBtn = e =>
        g(e, "cart_page_checkout", !0), window.ntcCartPagePayPalBtn = e => g(e, "cart_page_paypal", !0, !0), window
        .ntcCartNotificationCheckoutBtn = e => g(e, "cart_notification_checkout", !0), window.ntcCartNotificationPayPalBtn =
        e => g(e, "cart_notification_paypal", !0, !0), document.addEventListener("DOMContentLoaded", () => {
        const e = document.querySelector(".product-form__submit");
        e && e.addEventListener("click", t => {
            console.log("product form submit clicked"), P("ntcAddToCart")
        })
    });

    function M(e) {
        !Array.isArray(e) || e.length === 0 || ((function (t, o, r, n, a, c, i) {
            t.fbq || (a = t.fbq = function () {
                a.callMethod ? a.callMethod.apply(a, arguments) : a.queue.push(arguments)
            }, t._fbq || (t._fbq = a), a.push = a, a.loaded = !0, a.version = "2.0", a.queue = [],
                c = o.createElement(r), c.async = !0, c.src = n, i = o.getElementsByTagName(r)[0],
                i.parentNode.insertBefore(c, i))
        })(window, document, "script", "https://connect.facebook.net/en_US/fbevents.js"), e.forEach(t => {
            fbq("init", t)
        }))
    }

    function Y() {
        var e, t;
        try {
            const o = ((e = window.shopify) == null ? void 0 : e.order) || {},
                r = o.cart_info || {},
                n = Array.isArray(r.items) ? r.items : [],
                a = Number(r.items_subtotal_price || 0) / 100,
                c = o.currency || r.currency || "USD",
                i = (t = r.item_count) != null ? t : void 0,
                u = `initiatecheckout_${o.order_no}`,
                y = n.map(l => {
                    var d, f;
                    return (f = (d = l == null ? void 0 : l.variant_id) != null ? d : l == null ? void 0 : l.id) !=
                    null ? f : l == null ? void 0 : l.product_id
                }).filter(Boolean).map(String);
            window.fbq("track", "InitiateCheckout", {
                value: a,
                currency: c,
                content_ids: y,
                numItems: i,
                content_type: "product"
            }, {
                eventID: u
            })
        } catch (o) {
            console.error("fbq track InitiateCheckout error:", o)
        }
    }

    function V() {
        var e, t, o, r;
        try {
            const n = ((e = window.shopify) == null ? void 0 : e.order) || {},
                a = n.cart_info || {},
                c = Array.isArray(a.items) ? a.items : [],
                i = Number((o = (t = a.total_price) != null ? t : a.items_subtotal_price) != null ? o : 0) / 100,
                u = n.currency || a.currency || "USD",
                y = (r = a.item_count) != null ? r : void 0,
                l = `purchase_${n.order_no}`,
                d = c.map(f => {
                    var s, w;
                    return (w = (s = f == null ? void 0 : f.variant_id) != null ? s : f == null ? void 0 : f.id) !=
                    null ? w : f == null ? void 0 : f.product_id
                }).filter(Boolean).map(String);
            window.fbq("track", "Purchase", {
                value: i,
                currency: u,
                content_ids: d,
                num_items: y,
                content_type: "product"
            }, {
                eventID: l
            })
        } catch (n) {
            console.error("fbq track Purchase error:", n)
        }
    }(async function () {
        var t, o, r;
        try {
            const n = ((o = (t = window.shopify) == null ? void 0 : t.analytics) == null ? void 0 : o.facebook) ||
                    [],
                a = [...new Set(n.filter(c => c && c.enable === 1 && c.id).map(c => String(c.id)))];
            a.length > 0 && M(a), ((r = window.ntc) == null ? void 0 : r.page) === "checkout" && (await k(),
                Y()), window.addEventListener("ntcPurchase", async () => {
                await k(), V()
            })
        } catch (n) {
            console.error("FacebookPixel error:", n)
        }
    })(), document.addEventListener("ntcAddToCart", function () {
        const {
            ad_id: e,
            campaign_id: t,
            adset_id: o
        } = C(), r = {
            event_name: "AddToCart"
        };
        e && (r.ad_id = e), t && (r.campaign_id = t), o && (r.adset_id = o), _(
            `${window.ntcApiUrl}/api/facebook/ad_event`, {
                method: "POST",
                body: JSON.stringify(r),
                headers: {
                    "Content-Type": "application/json"
                }
            }).catch(n => {
            console.error("AddToCart event reporting failed:", n)
        })
    });

    function z(e) {
        !Array.isArray(e) || e.length === 0 || (function (t, o, r) {
            t.TiktokAnalyticsObject = r;
            var n = t[r] = t[r] || [];
            n.methods = ["page", "track", "identify", "instances", "debug", "on", "off", "once", "ready",
                "alias", "group", "enableCookie", "disableCookie", "holdConsent", "revokeConsent"], n.setAndDefer =
                function (c, i) {
                    c[i] = function () {
                        c.push([i].concat(Array.prototype.slice.call(arguments, 0)))
                    }
                };
            for (var a = 0; a < n.methods.length; a++) n.setAndDefer(n, n.methods[a]);
            n.instance = function (c) {
                for (var i = n._i[c] || [], u = 0; u < n.methods.length; u++) n.setAndDefer(i, n.methods[
                    u]);
                return i
            }, n.load = function (c, i) {
                var u = "https://analytics.tiktok.com/i18n/pixel/events.js";
                n._i = n._i || {}, n._i[c] = [], n._i[c]._u = u, n._t = n._t || {}, n._t[c] = +new Date,
                    n._o = n._o || {}, n._o[c] = i || {};
                var y = o.createElement("script");
                y.async = !0, y.src = u + "?sdkid=" + c + "&lib=" + r;
                var l = o.getElementsByTagName("script")[0];
                l.parentNode.insertBefore(y, l)
            }, e.forEach(c => n.load(c))
        })(window, document, "ttq")
    }

    function X() {
        var e, t, o;
        try {
            const r = (e = window.shopify) == null ? void 0 : e.order,
                n = (r == null ? void 0 : r.cart_info) || {},
                a = Array.isArray(n.items) ? n.items : [],
                c = (t = n.item_count) != null ? t : void 0,
                i = Number(n.items_subtotal_price || 0) / 100,
                u = (r == null ? void 0 : r.currency) || n.currency || "USD",
                y = a.filter(Boolean).map(d => {
                    var f, s;
                    return {
                        content_id: String((s = (f = d == null ? void 0 : d.variant_id) != null ? f : d == null ?
                            void 0 : d.id) != null ? s : d == null ? void 0 : d.product_id),
                        quantity: Number((d == null ? void 0 : d.quantity) || 1),
                        price: typeof (d == null ? void 0 : d.price) == "number" ? d.price / 100 : void 0
                    }
                }).filter(d => !!d.content_id),
                l = `initiatecheckout_${r.order_no}`;
            (o = window.ttq) == null || o.track("InitiateCheckout", {
                value: i,
                currency: u,
                contents: y,
                content_type: "product",
                quantity: c
            }, {
                event_id: l
            })
        } catch (r) {
            console.error("ttq track InitiateCheckout error:", r)
        }
    }

    function G() {
        var e, t, o, r, n;
        try {
            const a = ((e = window.shopify) == null ? void 0 : e.order) || {},
                c = a.cart_info || {},
                i = Array.isArray(c.items) ? c.items : [],
                u = Number((o = (t = c.total_price) != null ? t : c.items_subtotal_price) != null ? o : 0) / 100,
                y = a.currency || c.currency || "USD",
                l = (r = c.item_count) != null ? r : i.reduce((s, w) => s + Number((w == null ? void 0 : w.quantity) ||
                    0), 0),
                d = i.filter(Boolean).map(s => {
                    var F, U;
                    const w = String((U = (F = s == null ? void 0 : s.variant_id) != null ? F : s == null ?
                            void 0 : s.id) != null ? U : s == null ? void 0 : s.product_id),
                        N = Number((s == null ? void 0 : s.quantity) || 1),
                        x = typeof (s == null ? void 0 : s.price) == "number" ? s.price / 100 : void 0;
                    return x != null ? {
                        content_id: w,
                        quantity: N,
                        price: x
                    } : {
                        content_id: w,
                        quantity: N
                    }
                }).filter(s => !!s.content_id),
                f = `purchase_${a.order_no}`;
            (n = window.ttq) == null || n.track("Purchase", {
                value: u,
                currency: y,
                contents: d,
                content_type: "product",
                quantity: l
            }, {
                event_id: f
            })
        } catch (a) {
            console.error("ttq track Purchase error:", a)
        }
    }(async function () {
        var t, o, r;
        try {
            const n = ((o = (t = window.shopify) == null ? void 0 : t.analytics) == null ? void 0 : o.tiktok) ||
                    [],
                a = [...new Set(n.filter(c => c && c.enable === 1 && c.id).map(c => String(c.id)))];
            a.length && z(a), ((r = window.ntc) == null ? void 0 : r.page) === "checkout" && (await j(), X()),
                window.addEventListener("ntcPurchase", async () => {
                    await k(), G()
                })
        } catch (n) {
            console.error("initTikTokPixel error:", n)
        }
    })()
})();
